// 导入组件
import Header from '@/components/common/Header.vue';
import { initBaseUrl,request } from '../../utils/request';
import { getFullImageUrl } from '@/utils/request';
import { reverseGeocoder as mapReverseGeocoder } from '@/utils/mapUtils';
import authWin from '@/components/authWin/authWin.vue';
import { checkLogin } from '@/utils/authUtils';
export default {
  components: {
    Header,
    authWin
  },
  data() {
    return {
      latitude: 0,
      longitude: 0,
      headerData: {
        title: '兼职任务',
        subtitle: '附近有0个兼职任务' // 初始化为0，后续动态更新
      },
      distanceFilter: 'nearest',
      timeFilter: 'latest',
      salaryFilter: 'unlimited',
      activeMenu: '',
      // 筛选选项配置
      distanceOptions: [
        { text: '距离最近', value: 'nearest' },
        { text: '距离不限', value: 'unlimited' }
      ],
      timeOptions: [
        { text: '最新发布', value: 'latest' },
        { text: '最早发布', value: 'earliest' }
      ],
      salaryOptions: [
        { text: '酬金不限', value: 'unlimited' },
        { text: '酬金最高', value: 'highest' }
      ],
      // 兼职数据
      jobList: [],
      pageParams: {
        page: 1,
        pageSize: 10
      },
      isLoading: false,
      hasMore: true,
      // 分类列表
      categoryList: [],
      // 当前选中的分类
      currentCategory: 0,
      showEmergencyOrder: false,
      selectedRegion: {},
      localAddress: '定位中...',
      showApplySuccess: false,
      selectedAddress: '',
      isLocationFailed: false
    };
  },
  onShow() {
    // 从本地存储获取已选地区
    this.selectedRegion = uni.getStorageSync('selectedRegion') || {};
    
    // 不再在此页面检查实名认证状态，避免重复弹出
    // 实名认证弹窗只在登录后首次进入首页时显示一次
  },
  onLoad() {
    // 先获取经纬度再获取其他数据
    this.getLocation().then(() => {
      console.log("获取的经纬度", this.latitude, this.longitude);
      // 获取分类数据
      this.fetchCategories();
    });
    
    // 监听位置更新事件
    this.locationUpdateHandler = this.updateLocation.bind(this);
    this.$bus.$on('locationUpdated', this.locationUpdateHandler);
  },
  onUnload() {
    // 移除事件监听
    this.$bus.$off('locationUpdated', this.locationUpdateHandler);
  },
  computed: {
    distanceText() {
      return this.distanceFilter === 'nearest' ? '距离最近' : '距离不限';
    },
    timeText() {
      return this.timeFilter === 'latest' ? '最新发布' : '最早发布';
    },
    salaryText() {
      return this.salaryFilter === 'unlimited' ? '酬金不限' : '酬金最高';
    },
    selectedLocation() {
      if (this.selectedRegion.district) {
        return `${this.selectedRegion.district}`;
      } else if (this.selectedRegion.city) {
        return `${this.selectedRegion.city}`;
      }
      return this.localAddress;
    }
  },
  methods: {
    getFullImageUrl,
    async getLocation() {
      try {
        // 1. 获取经纬度
        const res = await uni.getLocation({
          type: 'gcj02',
          altitude: true,
          success: (res) => {
            this.latitude = res.latitude;
            this.longitude = res.longitude;
            // 2. 调用逆地理编码API
            this.reverseGeocoder(res.latitude, res.longitude).then(addressInfo => {
              console.log('详细地址:', addressInfo.address);
              this.localAddress = addressInfo.address;
              this.isLocationFailed = false;
            }).catch(error => {
              console.error('逆地理编码失败:', error);
              this.localAddress = '定位失败，点击重试';
              this.isLocationFailed = true;
            });
          },
          fail: (err) => {
            console.error('获取位置失败:', err);
            this.localAddress = '定位失败，点击重试';
            this.isLocationFailed = true;
            uni.showToast({
              title: '无法获取位置，请检查设置',
              icon: 'none'
            });
          }
        });
      } catch (err) {
        console.error('获取位置失败:', err);
        this.localAddress = '定位失败，点击重试';
        this.isLocationFailed = true;
        uni.showToast({
          title: '无法获取位置，请检查设置',
          icon: 'none'
        });
      }
    },

    // 逆地理编码方法
    async reverseGeocoder(latitude, longitude) {
      try {
        const addressInfo = await mapReverseGeocoder(latitude, longitude,true);
        return addressInfo;
      } catch (error) {
        console.error('逆地理编码失败:', error);
        throw error;
      }
    },

    // 更新位置信息
    updateLocation(locationData) {
        this.selectedAddress = locationData.address;
        this.latitude = locationData.latitude;
        this.longitude = locationData.longitude;
        this.localAddress = locationData.address;
        console.log('更新后的经纬度:', this.latitude, this.longitude);
        // 重新获取订单数据
        this.pageParams.page = 1;
        this.hasMore = true;
        this.fetchJobs();
    },

    // 导航到选择城市页面
    navigateToSelectedCity() {
      uni.navigateTo({
        url: '/pages/Receiveorders/selectedCity/selectedCity?fromPage=Receiveorders', // 对应pages.json中注册的路径
        success: () => {
          console.log('跳转选择城市页面成功');
        },
        fail: (err) => {
          console.error('跳转选择城市页面失败:', err);
        }
      });
    },
    // 处理报名状态切换

    async handleApply(job) {
      // 检查是否登录
      if (!checkLogin()) {
        uni.navigateTo({
          url: '/pages/pageLogin/index'
        });
        return;
      }

      // 先获取用户实名认证状态
      const userInfo = await this.fetchUserInfo();
      if (!userInfo.realname_verified) {
        this.$refs.authWinRef.openPopup();
        return;
      }

      // 调用报名接口
      request({
        url: 'Taskapply/apply_task',
        method: 'POST',
        data: {
          task_id: job.id
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.showApplySuccess = true;
            // 更新任务状态为已报名
            job.isApplied = true;
            setTimeout(() => {
              this.showApplySuccess = false;
            }, 2000);
          } else if (res.data.msg === '未实名') {
            // 未实名认证，显示认证弹窗
            this.$refs.authWinRef.openPopup();
          } else {
            uni.showToast({
              title: res.data.msg || '报名失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    handleFilterChange() {
      this.pageParams.page = 1; // 重置页码
      this.fetchJobs(); // 重新获取数据
    },
    toggleMenu(type) {
      this.activeMenu = this.activeMenu === type ? '' : type;
    },
    selectDistance(value) {
      this.distanceFilter = value;
      this.activeMenu = ''; // 清空菜单状态
      this.pageParams.page = 1; // 重置页码
      this.hasMore = true; // 重置加载更多状态
      this.fetchJobs(); // 立即调用数据刷新
    },
    selectTime(value) {
      this.timeFilter = value;
      this.activeMenu = '';
      this.pageParams.page = 1;
      this.hasMore = true;
      this.fetchJobs();
    },
    selectSalary(value) {
      this.salaryFilter = value;
      this.activeMenu = '';
      this.pageParams.page = 1;
      this.hasMore = true;
      this.fetchJobs();
    },
    // 获取分类数据
  fetchCategories() {
    this.isLoading = true;
    request({
      url: '/Category/list?parent_id=0',
      method: 'POST'
    }).then(res => {
      // 检查接口返回状态
      if (res.code === 200) {
        // 存储后端返回的分类数据
        this.categoryList = res.data.list;
        console.log(this.categoryList);

        // 默认选中全部分类
        this.currentCategory = 0;
        // 位置信息已经在onLoad中获取，直接加载数据
        this.filterJobsByCategory(0);
      } else {
        uni.showToast({ title: res.msg || '获取分类失败', icon: 'none' });
        this.categoryList = [];
      }
    }).catch(err => {
      console.error('获取分类失败:', err);
      uni.showToast({ title: '网络错误，无法加载分类', icon: 'none' });
      this.categoryList = [];
    }).finally(() => {
      this.isLoading = false;
    });
  },

    // 添加分类点击处理方法
    handleCategoryClick(categoryId) {
      this.currentCategory = categoryId; // 保持数值类型
      // 筛选对应分类的工作数据
      this.filterJobsByCategory(categoryId);
    },

    // 添加分类筛选方法
    filterJobsByCategory(categoryId) {
      // 重置页码
      this.pageParams.page = 1;

      // 根据分类ID筛选数据
      this.isLoading = true;
      request({
        url: '/Takeorders/workerList',
        method: 'POST',
        data: {  // 修改为params
          category_name: categoryId,
          page: this.pageParams.page,
          pageSize: this.pageParams.pageSize,
          distance: this.distanceFilter,
          time: this.timeFilter,
          salary: this.salaryFilter,
          lat: this.latitude,
          lng: this.longitude,
        }
      }).then(res => {
        this.isLoading = false;
        if (res.code === 200) {
          console.log('更新');
          this.jobList = res.data;
          // 更新任务数量
          this.headerData.subtitle = `附近有${res.data.length || 0}个兼职任务`;
          this.hasMore = res.data.page < res.data.total;
        }
      });
    },

    fetchJobs() {
      // 如果正在加载或没有更多数据，不执行请求
      if (this.isLoading || !this.hasMore) return;

      this.isLoading = true;
      // 合并分页参数和筛选参数
      const params = {
        ...this.pageParams,
        distance: this.distanceFilter,
        time: this.timeFilter,
        salary: this.salaryFilter,
        category_name: this.currentCategory,
        lat: this.latitude,
        lng: this.longitude,
      };

      request({
        url: '/Takeorders/workerList',
        method: 'POST',
        data: params  // 修改为params
      }).then(res => {
        const newJobs = res.data || [];
        // 第一页直接替换数据，后续页追加数据
        if (this.pageParams.page === 1) {
          this.jobList = newJobs;
          // 更新任务数量
          this.headerData.subtitle = `附近有${newJobs.length || 0}个兼职任务`;
        } else {
          this.jobList = this.jobList.concat(newJobs);
        }
        // 判断是否还有更多数据
        this.hasMore = newJobs.length === this.pageParams.pageSize;
      }).catch(err => {
        console.error('获取兼职数据失败', err);
      }).finally(() => {
        this.isLoading = false;
      });
    },

    // 关闭认证弹窗
    closeAuthWin() {
      // 可以在这里添加关闭弹窗后的逻辑
    },

    // 关闭紧急订单弹框
    closeEmergencyOrder() {
      this.showEmergencyOrder = false;
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const res = await request({
          url: '/User/info',
          method: 'GET'
        });

        if (res.code === 200 && res.data) {
          return res.data;
        }
        return { realname_verified: 0 };
      } catch (err) {
        console.error('获取用户信息错误:', err);
        return { realname_verified: 0 };
      }
    },

    onReachBottom() {

      // 触底时加载下一页
      if (this.hasMore && !this.isLoading) {
        console.log('触底了');
        this.pageParams.page++;
        console.log('当前页码', this.pageParams.page);
        this.fetchJobs();
      }
    }
  }
}
   